package com.shcowin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shcowin.biz.ContactBiz;
import com.shcowin.entity.Contact;

@Controller
@RequestMapping("/contact")
public class ContactController {

	@Inject
	private ContactBiz<Contact> contactBiz;

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> add(Contact contact) {
		if(contact.getId() != 0){
			contactBiz.edit(contact);
		}else{
			contactBiz.add(contact);
		}
		
		Map<String, Object> json = new HashMap<String, Object>();
		json.put("result", true);
		return json;
	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> edit(Contact Contact) {
		contactBiz.edit(Contact);
		Map<String, Object> json = new HashMap<String, Object>();
		json.put("result", true);
		return json;
	}

	@RequestMapping(value = "/get", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> getById(Integer id) {
		Contact Contact = contactBiz.getById(id);
		if (null == Contact) {
			return null;
		}
		Map<String, Object> json = new HashMap<String, Object>();
		json.put("Contact", Contact);
		return json;
	}

	@RequestMapping("/del")
	@ResponseBody
	public Map<String, Object> del(int id) {
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			contactBiz.del(id);
		} catch (Exception e) {
			json.put("result", false);
			return json;
		}
		json.put("result", true);
		return json;
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> list() {
		List<Contact> contactList = contactBiz.getAll();
		Map<String, Object> json = new HashMap<String, Object>();
		if (null != contactList && !contactList.isEmpty()) {
			json.put("contact", contactList.get(0));
		}
		return json;
	}
}
